<template>
  <div class="import-order">
    <div class="import-box">
      <!-- excel选择 -->
      <el-form label-position="left" label-width="90px">
        <el-row :gutter="5">
          <el-col :span="24">
            <el-form-item label="起使行：">
              <el-input-number
                v-model="xlsxConfig.startRow"
                :precision="0"
                :step="1"
                :min="0"
                :max="99999"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-input readonly :value="file.name" placeholder="请选择..." />
          </el-col>
          <el-col :span="6">
            <label for="file" class="el-button el-button--success el-button--medium">选择文件</label>
            <input
              type="file"
              id="file"
              class="input-file"
              accept=".xls, .xlsx"
              @change="handleChange"
            />
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="btn-group">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </div>
</template>

<script>
import XLSX from "xlsx";
export default {
  name: "import-order",
  components: {},
  props: {},
  data() {
    return {
      xlsxConfig: {
        startRow: 3 // 起始行，从1开始
      },
      file: {},
      formData: [],
      wb: null
    };
  },
  computed: {},
  watch: {},
  methods: {
    submit() {
      let file = this.file;
      let xlsxConfig = this.xlsxConfig;

      const reader = new FileReader();
      reader.onload = e => {
        const data = e.target.result;
        this.wb = XLSX.read(data, {
          type: "binary",
          header: "B"
        });
        const result = [];
        this.wb.SheetNames.forEach(sheetName => {
          result.push({
            sheetName: sheetName,
            sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName], {
              range: xlsxConfig.startRow - 1 // 设置起始行，从0开始所以要-1
            })
          });
        });
        console.log(result[0].sheet);

        this.$api.tradeforeign.createOrder(result[0].sheet).then(res => {
          this.$message.success('导入成功')
        });
      };
      reader.readAsBinaryString(file);
    },
    handleChange() {
      let fileInput = document.getElementById("file");
      let file = fileInput.files && fileInput.files[0];
      this.file = file || {};
      console.log(file);
    },
    close() {
      // 关闭表单弹框
      this.$emit("close");
    }
  },
  created() {}
};
</script>

<style lang="scss" scoped>
.import-order {
  .import-box {
    .input-file {
      display: none;
    }
  }
  .btn-group {
    text-align: center;
    margin-top: 30px;
  }
}
</style>